//
//  WBUserAccount.swift
//  weiboD
//
//  Created by gao2015 on 2016/12/4.
//  Copyright © 2016年 gao2015. All rights reserved.
//

import UIKit
//账号模型
class WBUserAccount: NSObject,NSCoding {
    //这是一个访问令牌
    var access_token : String?
    //access_token的过期时间,即多久过期
    var expires_in : TimeInterval = 0 {
        //在给expires_in赋值的时候计算过期日期
        didSet{
            expireDate = Date().addingTimeInterval(expires_in)
        }
    }
    
    //过期日期
    var expireDate : Date?
    
    //用户id
    var uid : Int64 = 0
    
    //用户名
    var name : String?
    //用户大图
    var avatar_large : String?
    
    init(dic:[String:Any]) {
    //现有对象
        super.init()
        setValuesForKeys(dic)
    }
    //防止字段过多
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
    }
    
    //归档
    func encode(with aCoder: NSCoder) {
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expireDate, forKey: "expireDate")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(name, forKey: "name")
        aCoder.encode(avatar_large, forKey: "avatar_large")
        
    }
    //解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObject(forKey: "access_token") as? String
        expireDate = aDecoder.decodeObject(forKey: "expireDate") as? Date
        uid = aDecoder.decodeInt64(forKey: "uid")
        name = aDecoder.decodeObject(forKey: "name") as? String
        avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String
    }
    
    //保存用户对象
    func saveUserAccount()  {
        let path = ((NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)).last! as NSString).appendingPathComponent("userAcountArchiver")
        //归档
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
        
    }
    //读取归档对象
    class func loadUserAccount() -> WBUserAccount?{
        let path = ((NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)).last! as NSString).appendingPathComponent("userAcountArchiver")
        let userAccount = NSKeyedUnarchiver.unarchiveObject(withFile: path)
        return userAccount as? WBUserAccount
    
    }
    
    
}
